import { request } from "../../utils/request";

//获取全局实例
const appInstance=getApp();
let backgroundAudioManager;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 标识音乐是否播放
        isPlay:false,
        musicData:{},
        current:"",
        currentTime:"",
        duration:"",
        durationFormat:"",
        isStart:false,
        showShare: false,
        options: [
          { name: '微信', icon: 'wechat', openType: 'share' },
          { name: '微博', icon: 'weibo' },
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
        ],
    },
    //音乐进度条拖动
    seek(e){
      this.backgroundAudioManager.seek(e.detail.value)
    },
    //收藏音乐
    async startMusic(){
      const isLogin = wx.getStorageSync('isLogin')
       if(isLogin){
          const musicId = this.data.musicData.id
          await request('/start',"POST",{musicId})
          this.setData({
            isStart:true
          })
          let startMapData = await request('/start/map')
          wx.setStorageSync('startMapList',startMapData.data);
       }else{
        wx.showToast({title:"请先登录" ,icon: 'error',duration: 1000})
       }
    },
    async cancelStart(){
      const isLogin = wx.getStorageSync('isLogin')
       if(isLogin){
          const musicId = this.data.musicData.id
          await request('/start/unstart',"POST",{musicId})
          this.setData({
            isStart:false
          })
          let startMapData = await request('/start/map')
          wx.setStorageSync('startMapList',startMapData.data);

       }else{
        wx.showToast({title:"请先登录" ,icon: 'error',duration: 1000})
       }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('detail',({ musicData }) =>{
        this.setData({musicData})
      })
     if(getApp().globalData.musicId == this.data.musicData.id){
         this.backgroundAudioManager =  appInstance.globalData.backgroundAudioManager
         let duration = Math.floor(this.backgroundAudioManager.duration)
         this.backgroundAudioManager.play()
         this.setData({
          duration,
          durationFormat:this.format(duration),
          isPlay:true
         })
     }else{
       // 创建控制音乐播放的实例
       this.backgroundAudioManager = wx.getBackgroundAudioManager()
       //将backgroundAudioManager实例保存到全局 globalData
       this.backgroundAudioManager.src = this.data.musicData.link
       this.backgroundAudioManager.startTime = 0
       appInstance.globalData.backgroundAudioManager = this.backgroundAudioManager
       appInstance.globalData.musicId = this.data.musicData.id
       this.handleMusicPlay()
       let playHistory = wx.getStorageSync("playHistory")
       let musicData = this.data.musicData
      if(musicData.author){
        if(playHistory.length>=10){
          playHistory.pop()
          playHistory.unshift(musicData)
        }else{
          playHistory.unshift(musicData)
        }
        wx.setStorageSync("playHistory",playHistory)
      }
     } 
     //播放中
     this.backgroundAudioManager.onTimeUpdate(()=>{
       let currentTime = Math.floor(this.backgroundAudioManager.currentTime)
       getApp().globalData.currentTime = currentTime
        this.setData({
          current:this.format(currentTime),
          currentTime
        })
     })
        // 监听音乐播放/暂停/停止
      this.backgroundAudioManager.onPlay(()=>{
        let duration = Math.floor(this.backgroundAudioManager.duration);
        getApp().globalData.isPlay = true
          this.setData({
              isPlay:true,
              duration,
              durationFormat:this.format(duration)
          })
      });

      //播放结束 自动播放下一首
      this.backgroundAudioManager.onEnded(()=>{
        let musicList = getApp().globalData.musicList
        let index = getApp().globalData.index
        // 创建控制音乐播放的实例
        this.backgroundAudioManager = wx.getBackgroundAudioManager()
        //设置src
        this.backgroundAudioManager.src = musicList[index].link
        //设置开始时间
        this.backgroundAudioManager.startTime = 0
         //将backgroundAudioManager实例保存到全局 globalData
        appInstance.globalData.backgroundAudioManager = this.backgroundAudioManager
        appInstance.globalData.musicId = this.data.musicData.id
        this.setData({
          musicData:musicList[index],
          isPlay:false
        })
        this.handleMusicPlay()
        getApp().globalData.index = index+1
      })
      this.backgroundAudioManager.onPause(()=>{
        getApp().globalData.isPlay = false
          this.setData({
              isPlay:false
          })
      });
      this.backgroundAudioManager.onStop(()=>{
        getApp().globalData.isPlay = false
          this.setData({
              isPlay:false
          })
      });
      const startMapList = wx.getStorageSync('startMapList');   
      let isStart = startMapList.some(item=>item.musicId == this.data.musicData.id)
      this.setData({
         isStart
      })
    },
    // 点击播放/暂停的回调
    handleMusicPlay(){
        let isPlay=!this.data.isPlay
        this.musicControl(isPlay)
    },

    musicControl(isPlay){
        if(isPlay){
          let link = this.data.musicData.link
          this.backgroundAudioManager.title=this.data.musicData.name
          this.backgroundAudioManager.src= link
            
        }else{
            // 音乐暂停
            this.backgroundAudioManager.pause()
        }
    },
    //格式化时间
    format(seconds) {
      let min = Math.floor(seconds / 60) >= 10 ? Math.floor(seconds / 60) : '0' + Math.floor(seconds / 60);
      seconds -= 60 * min;
      let sec = seconds >= 10 ? seconds : '0' + seconds;
      return min + ':' + sec;
    },
    preMusic(){
        let index = getApp().globalData.index -1
        let musicList = getApp().globalData.musicList
        let length = musicList.length
        if(index<=0){
          index = length-1
        }
        // 创建控制音乐播放的实例
        this.backgroundAudioManager = wx.getBackgroundAudioManager()
        //设置src
        this.backgroundAudioManager.src = musicList[index].link
        //设置开始时间
        this.backgroundAudioManager.startTime = 0
         //将backgroundAudioManager实例保存到全局 globalData
        appInstance.globalData.backgroundAudioManager = this.backgroundAudioManager
        appInstance.globalData.musicId = this.data.musicData.id
        
        this.setData({
          musicData:musicList[index],
          isPlay:false
        })
        this.handleMusicPlay()
        getApp().globalData.index = index
    },
    nextMusic(){
        let musicList = getApp().globalData.musicList
        let index = getApp().globalData.index + 1
        let length = musicList.length
        if(index>=length){
          index = 0
        }
        // 创建控制音乐播放的实例
        this.backgroundAudioManager = wx.getBackgroundAudioManager()
        //设置src
        this.backgroundAudioManager.src = musicList[index].link
        //设置开始时间
        this.backgroundAudioManager.startTime = 0
         //将backgroundAudioManager实例保存到全局 globalData
        appInstance.globalData.backgroundAudioManager = this.backgroundAudioManager
        appInstance.globalData.musicId = this.data.musicData.id
        this.setData({
          musicData:musicList[index],
          isPlay:false
        })
        this.handleMusicPlay()
        getApp().globalData.index = index
    },
    share(){
      this.setData({ showShare: true });
    
    },
    onClose() {
      this.setData({ showShare: false });
    },
    onSelect(event) {
      Toast(event.detail.name);
      this.onClose();
    },
})